package com.shanxi.cz.module.biz.framework.mqtt.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shanxi.cz.framework.common.util.date.LocalDateTimeUtils;
import com.shanxi.cz.module.biz.controller.admin.ammetermqtt.vo.AmmeterMqttSaveReqVO;
import com.shanxi.cz.module.biz.dal.dataobject.ammeterbasicinfo.AmmeterBasicInfoDO;
import com.shanxi.cz.module.biz.service.ammeterbasicinfo.AmmeterBasicInfoService;
import com.shanxi.cz.module.biz.service.ammetermqtt.AmmeterMqttService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MqttBusinessService {

    @Autowired
    private AmmeterBasicInfoService ammeterBasicInfoService;

    @Autowired
    private AmmeterMqttService ammeterMqttService;

    /**
     * 处理MQTT消息 - 异步处理避免阻塞
     */
    @Async("mqttTaskExecutor")
    public void processMessage(String topic, String payload) {
        try {
            log.debug("开始处理MQTT消息 - Topic: {}, Payload: {}", topic, payload);

            // 根据topic路由到不同的业务处理器
            switch (resolveTopicType(topic)) {
                case "ammeter":
                    handleBusiness(topic, payload);
                    break;
                default:
                    processUnknownMessage(topic, payload);
                    break;
            }

            log.info("MQTT消息处理完成 - Topic: {}", topic);

        } catch (Exception e) {
            log.error("处理MQTT消息异常 - Topic: {}, Error: {}", topic, e.getMessage(), e);
            handleProcessFailure(topic, payload, e);
        }
    }

    /**
     * 处理传感器数据
     */
    private void handleBusiness(String topic, String message) throws Exception {
        System.out.println("客户端接收消息内容 : " + message);
        AmmeterMqttSaveReqVO ammeterMqttSaveReqVO = generateAmmeterMqtt(message);

        // 将接收的消息内容序列化并入库
        List<AmmeterBasicInfoDO> ammeterBasicInfoAll = ammeterBasicInfoService.getAmmeterBasicInfoAll();
        Map<String, List<AmmeterBasicInfoDO>> ammeterBasicInfoGroupBySn = ammeterBasicInfoAll.stream().collect(Collectors.groupingBy(AmmeterBasicInfoDO::getAddress));
        if (ammeterBasicInfoGroupBySn.containsKey(ammeterMqttSaveReqVO.getAmmeterAddress())) {
            AmmeterBasicInfoDO ammeterBasicInfoDO = ammeterBasicInfoGroupBySn.get(ammeterMqttSaveReqVO.getAmmeterAddress()).get(0);
            ammeterMqttSaveReqVO.setAmmeterId(ammeterBasicInfoDO.getId());
            // 将mqtt消息存储到数据库中
            ammeterMqttService.createAmmeterMqtt(ammeterMqttSaveReqVO);
        }
    }

    private AmmeterMqttSaveReqVO generateAmmeterMqtt(String mqttInfo) {
        AmmeterMqttSaveReqVO ammeterMqttSaveReqVO = new AmmeterMqttSaveReqVO();
        JSONObject ammeterMqttJson = JSONObject.parseObject(mqttInfo);
        // 表号
        String id = ammeterMqttJson.getString("id");
        ammeterMqttSaveReqVO.setAmmeterAddress(id);

        // 记录日期
        String dateStr = LocalDateTimeUtils.getDateStr();
        ammeterMqttSaveReqVO.setRecordDate(dateStr);

        //        PT变比			PT
        //        CT变比			CT
        //        频率			Hz
        Double hz = ammeterMqttJson.getDouble("Hz");
        ammeterMqttSaveReqVO.setHz(hz);
        //        A相电流			Ia
        Double ia = ammeterMqttJson.getDouble("Ia");
        ammeterMqttSaveReqVO.setIa(ia);
        //        B相电流			Ib
        Double ib = ammeterMqttJson.getDouble("Ib");
        ammeterMqttSaveReqVO.setIb(ib);
        //        C相电流			Ic
        Double ic = ammeterMqttJson.getDouble("Ic");
        ammeterMqttSaveReqVO.setIc(ic);
        //        A相功率因数		PFa
        Double pfa = ammeterMqttJson.getDouble("PFa");
        ammeterMqttSaveReqVO.setPfa(pfa);
        //        B相功率因数		PFb
        Double pfb = ammeterMqttJson.getDouble("PFb");
        ammeterMqttSaveReqVO.setPfb(pfb);
        //        C相功率因数		PFc
        Double pfc = ammeterMqttJson.getDouble("PFc");
        ammeterMqttSaveReqVO.setPfc(pfc);
        //        三相总功率因数		PFs
        Double pfs = ammeterMqttJson.getDouble("PFs");
        ammeterMqttSaveReqVO.setPfs(pfs);
        //        三相总有功功率		Pall
        Double pall = ammeterMqttJson.getDouble("Pall");
        ammeterMqttSaveReqVO.setPall(pall);
        //        A相有功功率		Pa
        Double pa = ammeterMqttJson.getDouble("Pa");
        ammeterMqttSaveReqVO.setPa(pa);
        //        B相有功功率		Pb
        Double pb = ammeterMqttJson.getDouble("Pb");
        ammeterMqttSaveReqVO.setPb(pb);
        //        C相有功功率		Pc
        Double pc = ammeterMqttJson.getDouble("Pc");
        ammeterMqttSaveReqVO.setPc(pc);
        //        A相无功功率		Qa
        Double qa = ammeterMqttJson.getDouble("Qa");
        ammeterMqttSaveReqVO.setQa(qa);
        //        B相无功功率		Qb
        Double qb = ammeterMqttJson.getDouble("Qb");
        ammeterMqttSaveReqVO.setQb(qb);
        //        C相无功功率		Qc
        Double qc = ammeterMqttJson.getDouble("Qc");
        ammeterMqttSaveReqVO.setQc(qc);
        //        三相总无功功率		Qs
        Double qs = ammeterMqttJson.getDouble("Qs");
        ammeterMqttSaveReqVO.setQs(qs);
        //        A相视在功率		Sa
        Double sa = ammeterMqttJson.getDouble("Sa");
        ammeterMqttSaveReqVO.setSa(sa);
        //        B相视在功率		Sb
        Double sb = ammeterMqttJson.getDouble("Sb");
        ammeterMqttSaveReqVO.setSb(sb);
        //        C相视在功率		Sc
        Double sc = ammeterMqttJson.getDouble("Sc");
        ammeterMqttSaveReqVO.setSc(sc);
        //        三相总视在功率		Ss
        Double ss = ammeterMqttJson.getDouble("Ss");
        ammeterMqttSaveReqVO.setSs(ss);
        //        A相电压			Ua
        Double ua = ammeterMqttJson.getDouble("Ua");
        ammeterMqttSaveReqVO.setUa(ua);
        //        AB线电压			Uab
        Double uab = ammeterMqttJson.getDouble("Uab");
        ammeterMqttSaveReqVO.setUab(uab);
        //        B相电压			Ub
        Double ub = ammeterMqttJson.getDouble("Ub");
        ammeterMqttSaveReqVO.setUb(ub);
        //        BC线电压			Ubc
        Double ubc = ammeterMqttJson.getDouble("Ubc");
        ammeterMqttSaveReqVO.setUbc(ubc);
        //        C相电压			Uc
        Double uc = ammeterMqttJson.getDouble("Uc");
        ammeterMqttSaveReqVO.setUc(uc);
        //        CA线电压			Uca
        Double uca = ammeterMqttJson.getDouble("Uca");
        ammeterMqttSaveReqVO.setUca(uca);
        //        总能耗			eng
        Double eng = ammeterMqttJson.getDouble("eng");
        ammeterMqttSaveReqVO.setEng(eng);
        //        正向无功电能		engPoQ
        Double engpoq = ammeterMqttJson.getDouble("engPoQ");
        ammeterMqttSaveReqVO.setEngpoq(engpoq);
        //        反向有功电能		engNeP
        Double engnep = ammeterMqttJson.getDouble("engNeP");
        ammeterMqttSaveReqVO.setEngnep(engnep);
        //        反向无功电能		engNeQ
        Double engneq = ammeterMqttJson.getDouble("engNeQ");
        ammeterMqttSaveReqVO.setEngneq(engneq);
        return ammeterMqttSaveReqVO;
    }

    /**
     * 处理未知消息
     */
    private void processUnknownMessage(String topic, String payload) {
        log.info("未知主题消息 - Topic: {}, Payload: {}", topic, payload);
        // 可以保存到日志或特殊处理队列
    }

    /**
     * 解析主题类型
     */
    private String resolveTopicType(String topic) {
        if (topic.contains("/Iot/Pub")) return "ammeter";
        return "unknown";
    }

    /**
     * 处理处理失败的情况
     */
    private void handleProcessFailure(String topic, String payload, Exception e) {
        // 可以记录到失败队列、发送通知等
        log.error("消息处理失败，已记录到失败队列 - Topic: {}", topic);
        // failureQueueService.addFailureRecord(topic, payload, e.getMessage());
    }
}